package io.daocloud.prometheustestdemo.config;

import io.github.bucket4j.distributed.ExpirationAfterWriteStrategy;
import io.github.bucket4j.redis.lettuce.cas.LettuceBasedProxyManager;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;

/**
 * 限流配置
 */
@Configuration
@Slf4j
public class RateLimitConfig {
    
    @Value("${spring.redis.host:localhost}")
    private String redisHost;
    
    @Value("${spring.redis.port:6379}")
    private int redisPort;
    
    @Value("${rate.limit.requests-per-second:100}")
    private int requestsPerSecond;
    
    /**
     * Redis客户端配置
     */
    @Bean
    public RedisClient redisClient() {
        try {
            log.info("Creating Redis client for host: {}, port: {}", redisHost, redisPort);
            RedisURI redisURI = RedisURI.Builder
                    .redis(redisHost, redisPort)
                    .withTimeout(Duration.ofSeconds(3))  // 添加连接超时
                    .build();
            RedisClient client = RedisClient.create(redisURI);
            
            // 测试连接
            try {
                client.connect().sync().ping();
                log.info("Redis connection test successful");
            } catch (Exception e) {
                log.warn("Redis connection test failed, but client created: {}", e.getMessage());
            }
            
            return client;
        } catch (Exception e) {
            log.error("Failed to create Redis client: {}", e.getMessage());
            throw new RuntimeException("Redis client creation failed", e);
        }
    }
    
    /**
     * Bucket4j代理管理器配置
     */
    @Bean
    public LettuceBasedProxyManager proxyManager(RedisClient redisClient) {
        try {
            log.info("Creating Lettuce-based proxy manager");
            LettuceBasedProxyManager manager = LettuceBasedProxyManager.builderFor(redisClient)
                    .withExpirationStrategy(ExpirationAfterWriteStrategy.basedOnTimeForRefillingBucketUpToMax(Duration.ofSeconds(10)))
                    .build();
            log.info("Lettuce-based proxy manager created successfully");
            return manager;
        } catch (Exception e) {
            log.error("Failed to create Lettuce-based proxy manager: {}", e.getMessage());
            throw new RuntimeException("Proxy manager creation failed", e);
        }
    }
    
    public int getRequestsPerSecond() {
        return requestsPerSecond;
    }
} 